package com.lmh.framework.mvc;

import com.lmh.entity.User;
import com.lmh.framework.jwt.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JWTUtil.token);
//        System.out.println("------------------" + token);
        User user = JWTUtil.getUser(token);
        // 续约
        String newToken = JWTUtil.sign(user);
        // 将新的token存放到响应头
        response.setHeader(JWTUtil.token, newToken);
        // 将获取的用户信息（并不是所有，但足够用于查询）放到请求头，用于后续拦截器或控制器直接取得
        request.setAttribute("user", user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
